<template>
  <div class="g-bd4 f-cb">
    <el-row class="tac">
      <el-col :span="4">
        <div class="playlist-menu">
          <el-menu

            class="el-menu-vertical-demo"
            background-color="#F8F8F8"
            text-color="#000000"
            active-text-color="#BD161C"
            @select="handleSelect">
            <!--<el-submenu index="1">-->
              <!--<template slot="title">-->
                <!--<i class="el-icon-bell"></i>-->
                <!--<span>我的歌手</span>-->
              <!--</template>-->
              <!--<el-menu-item v-for="(item, index) in artists" :index="item">-->
                <!--{{item.name}}-->
              <!--</el-menu-item>-->
            <!--</el-submenu>-->
            <el-submenu index="2">
              <template slot="title">
                <i class="el-icon-goods"></i>
                <span>创建的歌单</span>
              </template>
              <el-menu-item v-for="(item, index) in playlistCreated" :index="item" class="playlist-menu-item">
                <img :src="changeUrlToResizeImg(item.coverImgUrl, 30)"
                       height="30"
                       width="30"
                       class="item-playlist-cover">
                {{item.name}}
              </el-menu-item>
            </el-submenu>
            <el-submenu index="3">
              <template slot="title">
                <i class="el-icon-star-on"></i>
                <span>收藏的歌单</span>
              </template>
              <el-menu-item v-for="(item, index) in playlistSubscribe" :index="item" class="playlist-menu-item">
                <img :src="changeUrlToResizeImg(item.coverImgUrl, 30)"
                     height="30"
                     width="30"
                     class="item-playlist-cover">
                {{item.name}}
              </el-menu-item>
            </el-submenu>
            <el-submenu index="4">
              <template slot="title">
                <i class="el-icon-setting"></i>
                <span>歌单管理</span>
              </template>
              <el-menu-item index="edit">
                编辑歌单
              </el-menu-item>
              <el-menu-item index="delete">
                删除歌单
              </el-menu-item>
              <el-menu-item index="add">
                添加歌单
              </el-menu-item>
            </el-submenu>
          </el-menu>
        </div>
      </el-col>
      <el-col :span="20">
        <div v-if="playlistId !== ''">
          <div class="playlist-detail" v-if="!isEdit">
            <song-sheet-detail v-if="hackReset" :playlistId="playlistId"></song-sheet-detail>
          </div>
          <div v-else>
            <div class="edit-playlist">

              <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="歌单名" prop="name">
                  <el-input v-model="ruleForm.name"></el-input>
                </el-form-item>
                <el-form-item label="介绍" prop="description">
                  <el-input type="textarea" v-model="ruleForm.description"></el-input>
                </el-form-item>
                <el-form-item label="上传封面">
                  <el-upload
                    v-loading="loading"
                    class="avatar-uploader"
                    :action="uploadServiceUrl"
                    :show-file-list="false"
                    :on-progress="handleProgress"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
                  <el-button @click="back()">取消</el-button>
                </el-form-item>
              </el-form>


            </div>
          </div>
        </div>

      </el-col>
    </el-row>

  </div>
</template>

<script>
  import {getUser} from "../util/userUtils"
  import {userCreatedPlaylists, userSubscribePlaylists, apiContext} from "../service/getData"

  import SongSheetDetail from '../components/songSheetDetail'
  import EditPlaylist from './editPlaylist'
  export default {
    name: 'myMusic',
    data() {
      return {
        uploadServiceUrl: "",
        playlistId: "",
        artists: [],
        playlistCreated: [],
        playlistSubscribe: [],
        playlistType: "create",
        playlistNow: {},
        user: {},
        hackReset: true,

        isEdit: false,
        imageUrl: null,
        imageId: null,
        ruleForm: {
          name: null,
          description: null
        },
        rules: {
          name: [
            { required: true, message: '请输入歌单名称', trigger: 'blur' },
            { min: 1, max: 20, message: '长度为 1~20 个字符', trigger: 'blur' }
          ],
          description: [
            { required: false, message: '请填写歌单介绍', trigger: 'blur' }
          ]
        },
        loading: false
      }
    },
    inject: ['reload'],
    methods: {
      changeUrlToResizeImg(picUrl, size) {
        return picUrl.replace(/yunmusic_dev/, "resize_" + size + 'x' + size);
      },
      back() {
        this.isEdit = false;
      },
      submitForm() {
        this.$http.post(apiContext+"playlist/update", {
          id: this.playlistId,
          name: this.ruleForm.name,
          description: this.ruleForm.description,
          coverImgId: this.imageId
        }, {
          emulateJSON : true,
          headers: {
            'Content-Type': 'x-www-form-urlencoded',
            'userId': this.user.id,
            'userToken': this.user.userToken
          }}).then(res => {
          console.log(res);
          let status = res.body.status;
          if (status === 200) {
            this.$message({
              message: "更新成功",
              type: 'success'
            });
            // 刷新用户创建的歌单
            // this.getCreatedPlaylists();
            this.reload();
          } else {
            this.$message({
              message: res.body.msg,
              type: 'error'
            });
          }
        })
      },
      handleProgress(event, file, fileList) {
        this.loading = true;
      },
      handleAvatarSuccess(res, file) {
        console.log(res);
        this.loading = false;
        if (res.status === 200) {
          this.$message.success("上传成功");
          let data = res.data;
          this.imageUrl = data.filePath;
          // this.imageUrl = data.filePath;
          this.imageId = data.fileId;
        } else {
          this.$message.error(res.msg);
        }
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      getCreatedPlaylists() {
        console.log(this.user)
        userCreatedPlaylists(this).get({
          id: this.user.id
        }).then(res => {
          console.log(res);
          if (res.body.status === 200) {
            this.playlistCreated = res.body.data.rows;
          }
        })
      },
      getSubsribedPlaylists() {
        console.log(this.user)
        userSubscribePlaylists(this).get({
          id: this.user.id
        }).then(res => {
          console.log("getSubsribedPlaylists")
          console.log(res);
          if (res.body.status === 200) {
            this.playlistSubscribe = res.body.data.rows;
          }
        })
      },
      deletePlaylist() {
        this.$confirm('此操作将永久删除该歌单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let userId = this.user.id;
          let userToken = this.user.userToken;
          this.$http.post(apiContext+"playlist/delete", {
            playlistId: this.playlistId,
          }, {
            emulateJSON : true,
            headers: {
              'Content-Type': 'x-www-form-urlencoded',
              'userId': userId,
              'userToken': userToken
            }}).then(res => {
            console.log(res);
            let status = res.body.status;
            if (status === 200) {
              this.$message({
                message: "删除成功",
                type: 'success'
              });
              // 刷新用户创建的歌单
              // this.getCreatedPlaylists();
              this.reload();
            } else {
              this.$message({
                message: res.body.msg,
                type: 'error'
              });
            }
          })

        }).catch(() => {

        });

      },
      createNewPlaylist() {
        let userId = this.user.id;
        let userToken = this.user.userToken;
        this.$prompt('请输入歌单名', '创建新歌单', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          this.$http.post(apiContext+"playlist/publish", {
            userId: userId,
            name: value,
          }, {
            emulateJSON : true,
            headers: {
              'Content-Type': 'x-www-form-urlencoded',
              'userId': userId,
              'userToken': userToken
            }}).then(res => {
            console.log(res);
            let status = res.body.status;
            if (status === 200) {
              this.$message({
                message: "创建成功",
                type: 'success'
              });
              // 刷新用户创建的歌单
              this.getCreatedPlaylists();
            } else {
              this.$message({
                message: res.body.msg,
                type: 'error'
              });
            }
          })
        }).catch(() => {

        });
      },
      handleSelect(key, keyPath) {
        console.log(keyPath);

        if (keyPath[0] === '4' && keyPath[1] === 'edit') {
          this.isEdit = true;

        } else {
          this.isEdit = false;
        }
        if (keyPath[0] === '2') {
          console.log(key);
          this.playlistId = key.id;
          this.playlistType = "create"
          this.playlistNow = key;
          this.ruleForm.name = key.name;
          this.ruleForm.description = key.description;
          this.imageUrl = key.coverImgUrl;
          // 刷新歌单详情
          this.hackReset = false;
          this.$nextTick(() => {
            this.hackReset = true
          })
        } else if (keyPath[0] === '3') {
          this.playlistId = key.id;
          this.playlistType = "subscribe"
          console.log(key);
          // 刷新歌单详情
          this.hackReset = false;
          this.$nextTick(() => {
            this.hackReset = true
          })
        } else if (keyPath[0] === '4') {
          if (keyPath[1] === 'edit') {
            this.isEdit = true;
          } else if (keyPath[1] === 'delete') {
            if (this.playlistType === 'create') {
              this.deletePlaylist();
            } else if (this.playlistType === 'subscribe'){
              this.$message({
                message: "收藏的歌单不能删除，只能取消收藏",
                type: 'info'
              });
            }
          } else if (keyPath[1] === 'add') {
            this.createNewPlaylist();
          }
        }

      }
    },
    mounted() {
      this.uploadServiceUrl = apiContext + "/playlist/uploadCover"
      this.user = getUser();
      this.getCreatedPlaylists();
      this.getSubsribedPlaylists();
    },
    components: {EditPlaylist, SongSheetDetail}
  }
</script>

<style scoped>
  .g-bd, .g-bd1, .g-bd2, .g-bd3, .g-bd4, .g-bd5, .g-bd6, .g-bd7 {
    width: 980px;
    min-height: 700px;
    _height: 700px;
    margin: 0 auto;
    background-color: #fff;
    border: 1px solid #d3d3d3;
    border-width: 0 1px;
  }

  .g-bd4 {
    background: url(../image/wrap2.png) repeat-y center 0;
  }

  .f-cb:after {
    clear: both;
    content: '.';
    display: block;
    height: 0;
    visibility: hidden;
  }

  .playlist-detail {
    margin-left: 10px;
  }

  .playlist-menu {
    /*display: inline-block;*/
    margin-right: -18px;
  }

  .playlist-menu-item {
    /*display: inline;*/
    /*width: 200px;*/
    font-size: 10px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .playlist-menu-item-right {
    display: inline-block;
  }

  .playlist-name {
    font-size: 10px;
    /*overflow: hidden;*/
    /*white-space: nowrap;*/
    /*text-overflow: ellipsis;*/
  }

  .playlist-cover {
    display: inline;
  }

  .edit-playlist {
    margin-top: 30px;
    margin-right: 30px;
  }

  .avatar-uploader {
    width: 178px;
    height: 178px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>
